package com.naiterui.ehp.bs.emr.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.naiterui.ehp.bp.bo.smh.SmhUserBO;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.encypt.MD5;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.emr.service.ISmhService;
import com.naiterui.ehp.bs.emr.utils.his.HisApi;
import com.naiterui.ehp.bs.emr.utils.his.param.resp.MedicalResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 接口
 *
 * @author guoyongxiang
 * @version 1.0.0
 * @date 2021/8/12 17:04
 **/
@Slf4j
@Service
public class SmhServiceImpl implements ISmhService {

    private static final String API_GET_PATIENT_LIST_BY_IDS =
            "/pnx-gateway/pnx-medical-api/hisapi/NetHis/GetPatientListByIds";

    @Override
    public List<SmhUserBO> getPatientListByIds(Map<String, String> inquirerMap) throws BusinessException {
        // 客户HIS厂商未提供独立批量查询复诊患者接口
        return inquirerMap.keySet().stream().map(idCard -> {
            String name = inquirerMap.get(idCard);
            List<MedicalResp> medicals = null;
            try {
                medicals = HisApi.getMedical(idCard, name);
            } catch (BusinessException e) {
                log.warn(e.getMessage() + "idCard:{}", idCard);
                return null;
            }
            if (CollectionUtils.isEmpty(medicals)) {
                return null;
            }
            return idCard;
        }).filter(StringUtils::isNotBlank).map(SmhUserBO::new).collect(Collectors.toList());
    }

    private String getHaosenHisUrl(String idCard) {
        // 接口参数
        Map<String, String> params = Maps.newHashMap();
        params.put("appid", ConfigUtil.getString("his.appid"));
        params.put("appsecret", ConfigUtil.getString("his.appSecret"));
        params.put("idNo", idCard);

        // 公共参数
        Map<String, String> commonParam = Maps.newHashMap();
        commonParam.put("data", Base64.encode(JSON.toJSONString(params)));
        commonParam.put("nonce", UUID.randomUUID().toString().replace("-", ""));
        commonParam.put("timestamp", System.currentTimeMillis() + "");

        // 生成签名
        StringBuilder builder = new StringBuilder();
        builder.append("data=").append(commonParam.get("data"));
        builder.append("&nonce=").append(commonParam.get("nonce"));
        builder.append("&timestamp=").append(commonParam.get("timestamp"));
        String sign = MD5.md5(builder.toString());
        commonParam.put("sign", sign);

        String url = ConfigUtil.getString("his.url");
        String result = HttpRequest.post(url).header("firmId", ConfigUtil.getString("his.appid")).body(JSON.toJSONString(commonParam)).execute().body();
        System.out.println(result);
        JSONObject jsonObject = JSON.parseObject(result);
        Integer code = jsonObject.getInteger("code");
        String h5Url = null;
        if (code == 20000) {
            h5Url = jsonObject.getJSONObject("data").getString("url");
        } else {
            log.warn("获取HIS就诊记录失败 result:{}", result);
        }
        return h5Url;
    }
}
